$(function() {

    $(document).ready(function() {

        var eventDrag = function(el) {
            var eventObject = {
                title: $.trim(el.text()),
            };
            eventObject.className = el.attr('data-color');
            eventObject.user_id = el.attr('data-id');
            eventObject.group_id = el.attr('data-group');
            eventObject.group_name = el.attr('data-group-name');
            el.data('eventObject', eventObject);
            el.draggable({
                zIndex: 999,
                revert: true,
                revertDuration: 0
            });
        }

        $('#external-events div.external-event').each(function() {
            eventDrag($(this));
        });
        $('#calendar_arrangement').fullCalendar({
            header: {
                left: 'prev today next ',
                center: 'title',
                right: '' //month,agendaWeek,agendaDay
            },
            weekMode: 'liquid',
            editable: true,
            droppable: true,
            dragOpacity: {
                '': .6
            },
            buttonText: {
                today: '本月',
                month: '月',
                agendaWeek: '周',
                agendaDay: '日'
            },
            monthNames: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
            monthNamesShort: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
            dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
            dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
            firstDay: 1,
            titleFormat: {
                month: 'yyyy年MMMM',
                week: "yyyy/MMM/d{ '— '[ yyyy/][MMM/]d}",
                day: 'yyyy/MMM/d dddd'
            },
            columnFormat: {
                month: 'ddd',
                week: 'M/d ddd',
                day: 'M/d dddd'
            },
            allDayText: '全天',

            //获取数据后显示在fullcalendar页面
            events: function(start, end, callback) {
                var fstart = $.fullCalendar.formatDate(start, "yyyy-MM-dd");
                var fend = $.fullCalendar.formatDate(end, "yyyy-MM-dd");
                $.ajax({
                    type: "post",
                    url: "index.php?m=setting&a=getArrangement",
                    dataType: "json",
                    data: {
                        start: fstart,
                        end: fend
                    },
                    success: function(data) {
                        if (data) {
                            var event = [];
                            $.each(data, function(i) {
                                event.push({
                                    _id: data[i].event_id,
                                    title: data[i].title,
                                    start: data[i].start,
                                    end: data[i].end,
                                    className: data[i].color,
                                    group_id: data[i].group_id,
                                    group_name: data[i].group_name,
                                    user_id: data[i].user_id,
                                    allDay: true
                                });
                            });
                            callback(event);
                        }
                    }
                });
            },

            //点击时触发
            eventClick: function(event) {
                layer.confirm('确定要删除吗？', {
                    icon: 7,
                    title: '提示'
                }, function(index) {
                    //删除
                    $.post('index.php?m=setting&a=arrangement&type=delete', {
                        event_id: event._id
                    });
                    $('#calendar_arrangement').fullCalendar('removeEvents', event._id);
                    layer.close(index);
                }, function(index) {
                    layer.close(index);
                });
            },
            //移动时触发
            eventDrop: function(event) {
               sendArrangeData(event,'modify'); 
            },

            //拉伸时触发
            eventResize: function(event) {
               sendArrangeData(event,'modify');    
            },
            //排班时触发
            drop: function(date, allDay) {
                var originalEventObject = $(this).data('eventObject');

                var date = $.fullCalendar.formatDate(date, 'yyyy-MM-dd');
                var copiedEventObject = $.extend({}, originalEventObject);
                copiedEventObject.start_date = date;
                createEventId(copiedEventObject);
                var myObj = $("#calendar_arrangement").fullCalendar('clientEvents');
                //添加
                sendArrangeData(copiedEventObject,'add');
				
                if ($('#drop-remove').is(':checked')) {
                    $(this).remove();
                }
            }
        });

    });

    $(".panel").css("padding-bottom", "120px");
    /**
     * func        createEventId
     * description 创建一个eventID
     * param       event
     * return      void
     * author      qiandongjun@southtel.cn
     * date        2016-12-13
     **/
    function createEventId(event) {
        if (typeof event == 'object') {
            var user_id = event.user_id,
                group_id = event.group_id;
            if (user_id && group_id) {
                var date = new Date();
                var prefix = date.getFullYear();
                prefix += '' + (date.getMonth()+1) + '' + date.getDate();
                prefix += '' + date.getHours() + '' + date.getMinutes()
                prefix += '' + date.getSeconds() + '' + date.getMilliseconds();
                event._id = prefix + group_id + user_id;
            }
        }
    }
	  /**
     * func        sendArrangeData
     * description 整理数据，发送给后台处理
     * param       event,type
     * return      void
     * author      qiandongjun@southtel.cn
     * date        2016-12-14                   
     **/
	function sendArrangeData(event,request_type)
	{
		var postData = {
			   event_id:event._id,
			   user_id:event.user_id,
			   user_name:event.title,
			   group_id:event.group_id,
			   group_name:event.group_name,
			   type:request_type
			   
			};
		switch(request_type)
		{
		  case 'add':
		    postData['date']  = event.start_date;
			postData['color'] = event.className;
		  break;
		  case 'modify':
		    postData['start'] = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd");
			postData['end']   = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd");
			postData['color'] = event.className[0];
		  break;	
		}
	    $.ajax({
			type: "post",
			url: "index.php?m=setting&a=arrangement",
			data:postData,
			error: function(msg) {
			},
			beforeSend: function(xhr) {	
			},
			success: function(data) {
				if (data.status == 2) {
					layer.msg(data.info, {
						icon: 5
					});
					if(request_type == 'modify')
					{
					  $('#calendar_arrangement').fullCalendar('refetchEvents');	
					}
				} else {
					  $('#calendar_arrangement').fullCalendar('refetchEvents');
				}
			}
		});	
	}
});